<?php

class CustProductSitesController extends AppController {

    var $name = 'CustProductSites';
    var $uses = array('CustProductSite', 'Product', 'Brand', 'Supplier', 'Category', 'Customer', 'Site', 'CustomerSupplier');
    var $viewPath = 'customers/inventories/cust_product_sites';
    var $pageTitle = 'Product Inventory';
    var $paginate = array('CustProductSite' => array('order' => array('CustProductSite.stock_code')));
    /**
     * สำหรับ Site user ที่มีสิทธิ์ can_view_other_site เลือกดูข้อมูล site อื่น
     * @var int site id ที่ต้องการดู
     */
    var $viewSiteInventoryId = null;

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'cust_product_sites');
        $this->set('tabMenu', 'tabmenus/customer/inventories');
        $this->viewSiteInventoryId = $this->Session->check('Auth.User.Extend.view_site_inventory') ?
                $this->Session->read('Auth.User.Extend.view_site_inventory') : $this->Auth->user('site_id');
    }

    function display() {
        $this->set('site_id', $this->viewSiteInventoryId);

        // ดึงรายชื่อ Supplier ที่มีคลังอยู่ที่ Vendor เท่านั้น (consignment ใหม่) มาเก็บไว้ใน Session จะได้ไม่ต้อง ดึง DB ทุกครั้ง
        if (!$this->Session->check("{$this->name}.suppliers")) {
            $suppliers = $this->CustomerSupplier->listSupplierByCustomerId($this->Auth->user('customer_id'), array('has_supplier_inventory' => true));
            $this->Session->write("{$this->name}.suppliers", array_keys($suppliers));
        }
    }

    function display_site() {
        parent::display('CustProductSite');

        $this->_checkCustom('CustProductSite', array(
            'customer_id' => $this->Auth->user('customer_id'),
            'site_id' => $this->viewSiteInventoryId,
            'discontinued' => false, // เฉพาะรายการที่ยังใช้งานอยู่
        ));

        // ถ้ามาจาก supplier filter เฉพาะ product ที่ supplier นี้ dispatch ให้เท่านั้น
        if ($this->Session->read('Auth.User.Extend.from_supplier') == true) {
            $this->_checkCustom('CustProductSite', array(
                'supplier_id' => $this->Auth->user('supplier_id'),
                'dispatch_from' => SUPPLIER_PREFIX,
            ));
        } else {
            // แสดงเฉพาะสินค้าของ vendor ที่มีคลังที่ลูกค้า
            $invAtSuppliers = $this->Session->read("{$this->name}.suppliers");
            $this->paginate['CustProductSite']['conditions']['not']['CustProductSite.supplier_id'] = $invAtSuppliers;
        }

        $op = $this->_searchOperations();

        if (!empty($this->data['CustProductSite'])) {
            if (!empty($this->data['CustProductSite']['stock_code'])) {
                $this->Session->write('Criteria.stock_code', $this->data['CustProductSite']['stock_code']);
            }

            // หน้า search ปกติมี search ตามจำนวนและวันที่ด้วย
            // แต่หน้า search ที่มาจาก popup_view จะไม่มี Operand และวันที่
            if (!empty($this->data['Operand'])) {
                if ($this->data['CustProductSite']['current_stock'] != null) {
                    $this->Session->write('Criteria.current_stock', $this->data['CustProductSite']['current_stock']);
                    $this->Session->write('Operand.current_stock', $this->data['Operand']['current_stock']);
                }

                if ($this->data['CustProductSite']['reserve_qty'] != null) {
                    $this->Session->write('Criteria.reserve_qty', $this->data['CustProductSite']['reserve_qty']);
                    $this->Session->write('Operand.reserve_qty', $this->data['Operand']['reserve_qty']);
                }

                if ($this->data['CustProductSite']['min_stock'] != null) {
                    $this->Session->write('Criteria.min_stock', $this->data['CustProductSite']['min_stock']);
                    $this->Session->write('Operand.min_stock', $this->data['Operand']['min_stock']);
                }

                if ($this->data['CustProductSite']['max_stock'] != null) {
                    $this->Session->write('Criteria.max_stock', $this->data['CustProductSite']['max_stock']);
                    $this->Session->write('Operand.max_stock', $this->data['Operand']['max_stock']);
                }
                if (!empty($this->data['CustProductSite']['last_stock_in_date_start'])) {
                    $this->Session->write('Criteria.last_stock_in_date_start', $this->data['CustProductSite']['last_stock_in_date_start']);
                    $this->Session->write('Criteria.last_stock_in_date_end', $this->data['CustProductSite']['last_stock_in_date_end']);
                }

                if (!empty($this->data['CustProductSite']['last_stock_out_date_start'])) {
                    $this->Session->write('Criteria.last_stock_out_date_start', $this->data['CustProductSite']['last_stock_out_date_start']);
                    $this->Session->write('Criteria.last_stock_out_date_end', $this->data['CustProductSite']['last_stock_out_date_end']);
                }
            }


            if (!empty($this->data['CustProductSite']['dispatch_from'])) {
                $this->Session->write('Criteria.dispatch_from', $this->data['CustProductSite']['dispatch_from'] == 'its' ? $this->requestAction('system_preferences/get/company_name') : 'Other Vendor');
            }

            if (!empty($this->data['CustProductSite']['supplier_id'])) {
                $this->Supplier->id = $this->data['CustProductSite']['supplier_id'];
                $this->Session->write('Criteria.dispatch_from', $this->Supplier->field('name'));
            }
        }

        if (!empty($this->data['Product'])) {

            if (!empty($this->data['Product']['brand_id'])) {
                $this->Brand->id = $this->data['Product']['brand_id'];
                $this->Session->write('Criteria.brand_name', $this->Brand->field('name'));
            }

            if (!empty($this->data['Product']['part_no'])) {
                $this->Session->write('Criteria.part_no', $this->data['Product']['part_no']);
            }

            if (!empty($this->data['Product']['title'])) {
                $this->Session->write('Criteria.title', $this->data['Product']['title']);
            }

            if (!empty($this->data['Product']['text'])) {
                $this->Session->write('Criteria.text', $this->data['Product']['text']);
            }

            if (!empty($this->data['Product']['model'])) {
                $this->Session->write('Criteria.model', $this->data['Product']['model']);
            }

            if (!empty($this->data['Product']['category_id'])) {
                $this->Category->id = $this->data['Product']['category_id'];
                $this->Session->write('Criteria.category_name', $this->Category->field('name'));
            }

            // ถ้ามีการ search part no ให้หาจาก supplier part no ด้วย
            if (!empty($this->data['Product']['part_no'])) {
                $this->paginate['CustProductSite']['conditions']['OR']['Product.supplier_part_no LIKE'] = '%' . strtoupper(trim($this->data['Product']['part_no'], 'utf8')) . '%';
                $this->paginate['CustProductSite']['conditions']['OR']['Product.part_no LIKE'] = '%' . strtoupper(trim($this->data['Product']['part_no'], 'utf8')) . '%';
                unset($this->data['Product']['part_no']);
            }
        }
        if ($this->referer() == '/cust_product_sites') {
            $this->_checkBetweenSearch('CustProductSite', 'last_stock_in_date');
            $this->_checkBetweenSearch('CustProductSite', 'last_stock_out_date');
        }
        $this->paginate['CustProductSite']['contain'] = array('Site',
            'Product.Supplier', 'Product.Category', 'Product.Brand', 'Product.supplier_part_no', 'Product.part_no', 'Product.model', 'Product.title', 'Product.text',
            'ProductSerial' => array('CustLocation', 'limit' => 1, 'order' => 'stock_out_priority')
        );
        $this->_paging('CustProductSite', $op);
    }

    /**
     * แสดงข้อมูล Product ทุก Site ของ Customer นี้
     */
    function display_all() {
        $conditions = $this->data;

        // ดึงรายการ Site ที่มีทั้งหมดของ Customer นี้
        $sites = $this->CustProductSite->Site->find('all', array(
                    'conditions' => array('customer_id' => $this->Auth->user('customer_id')),
                    'contain' => array()
                ));

        $conditions = array();
        $conditions['customer_id'] = $this->Auth->user('customer_id');

        if (!empty($this->data['CustProductSite'])) {

            if (!empty($this->data['CustProductSite']['stock_code'])) {
                $conditions['stock_code'] = $this->data['CustProductSite']['stock_code'];
                $this->Session->write('Criteria.stock_code', $this->data['CustProductSite']['stock_code']);
            }

            if (!empty($this->data['CustProductSite']['dispatch_from'])) {
                $conditions['dispatch_from'] = $this->data['CustProductSite']['dispatch_from'];
                $this->Session->write('Criteria.dispatch_from', $this->data['CustProductSite']['dispatch_from'] == 'its' ? $this->requestAction('system_preferences/get/company_name') : 'Other Vendor');
            }

            if (!empty($this->data['CustProductSite']['supplier_id'])) {
                $conditions['supplier_id'] = $this->data['CustProductSite']['supplier_id'];
                $this->Supplier->id = $this->data['CustProductSite']['supplier_id'];
                $this->Session->write('Criteria.dispatch_from', $this->Supplier->field('name'));
            }
        }

        if (!empty($this->data['Product'])) {

            if (!empty($this->data['Product']['brand_id'])) {
                $this->Brand->id = $this->data['Product']['brand_id'];
                $this->Session->write('Criteria.brand_name', $this->Brand->field('name'));
            }

            if (!empty($this->data['Product']['part_no'])) {
                $this->Session->write('Criteria.part_no', $this->data['Product']['part_no']);
            }

            if (!empty($this->data['Product']['category_id'])) {
                $this->Category->id = $this->data['Product']['category_id'];
                $this->Session->write('Criteria.category_name', $this->Category->field('name'));
            }
        }

        unset($this->data['CustProductSite']);
        parent::display('Product');
        $product_ids = $this->CustProductSite->listProductIdByCustomerId($this->Auth->user('customer_id'), $conditions);

        $this->paginate['Product']['contain'] = array();
        $this->paginate['Product']['conditions']['Product.id'] = $product_ids;

        if (!empty($this->data['Product']) && !empty($this->data['Product']['part_no'])) {
            $this->paginate['Product']['conditions']['OR']['Product.part_no LIKE'] = '%' . trim($this->data['Product']['part_no'] . '%');
            $this->paginate['Product']['conditions']['OR']['Product.supplier_part_no LIKE'] = '%' . trim($this->data['Product']['part_no'] . '%');
            unset($this->data['Product']['part_no']);
        }

        $op = $this->_searchOperations();
        $this->_paging('Product', $op);
        $products = &$this->data;

        foreach ($products as &$product) {
            foreach ($sites as $site) {
                $site_id = $site['Site']['id'];
                $cps = $this->CustProductSite->find('first', array(
                            'conditions' => array(
                                'product_id' => $product['Product']['id'],
                                'site_id' => $site_id
                            ),
                            'contain' => array()
                        ));
                $product[$site_id] = $cps;
            }
        }
        $this->set('sites', $sites);
    }

    function view($id = null) {
        if ($id != null) {
            $this->CustProductSite->contain(array('Product' => array('Category', 'Brand', 'Unit'), 'ShortestPeriod', 'MaintenancePeriod', 'CyclePeriod', 'Supplier'));
            $this->data = $this->CustProductSite->findById($id);

            $this->_neighbors($id, $this->CustProductSite, array(
                'field' => 'stock_code', 'value' => $this->data['CustProductSite']['stock_code'],
                'fields' => array('id', 'stock_code'),
                'contain' => array('Site',
                    'Product.Supplier', 'Product.Category', 'Product.Brand', 'Product.supplier_part_no', 'Product.part_no', 'Product.model', 'Product.title', 'Product.text',
                    'ProductSerial' => array('CustLocation', 'limit' => 1, 'order' => 'stock_out_priority')
                    ))
            );
        }
    }

    function _searchOperations() {
        return array(
            'CustProductSite.stock_code' => 'LIKE',
            'Product.brand_id' => '=',
            'Product.category_id' => '=',
            'Product.model' => 'LIKE',
            'Product.title' => 'LIKE',
            'Product.text' => 'LIKE',
            'customer_id' => '=',
            'site_id' => '=',
            'supplier_id' => '=',
            'current_stock' => !empty($this->data['Operand']['current_stock']) ? $this->data['Operand']['current_stock'] : '>',
            'reserve_qty' => !empty($this->data['Operand']['reserve_qty']) ? $this->data['Operand']['reserve_qty'] : '>',
            'min_stock' => !empty($this->data['Operand']['min_stock']) ? $this->data['Operand']['min_stock'] : '>',
            'max_stock' => !empty($this->data['Operand']['max_stock']) ? $this->data['Operand']['max_stock'] : '>',
        );
    }

    /**
     * เปลี่ยน view site inventory
     */
    function change_view_site() {
        // clear ค่าการ search จาก Site เก่าออก
        $site_id = empty($this->data['view_site_inventory']) ? 'All' : $this->data['view_site_inventory'];

        $this->Session->delete($this->name);

        $this->Session->delete('CustProductSite.paging');

        // เงื่อนไขตอน Search เอาไป print
        $this->Session->delete('Criteria');

        $this->Session->write('Auth.User.Extend.view_site_inventory', $site_id);
        $this->Session->delete('CustProductSites.paging');
        $this->Session->delete('CustProductSite.paging');
        $this->Session->delete('Product.paging');
        $this->redirect('cust_product_sites/display');
    }

    function popup_search() {
        parent::popup_search();
        $this->set('operands', array('<' => '<', '<=' => '<=', '=' => '=', '>' => '>', '>=' => '>='));
        $this->set('popupWidth', '700');

        $this->set('categories', $this->Category->listCategoryBySiteOrSupplier($this->Auth->user('site_id'), $this->Auth->user('supplier_id')));

        $suppliers = $this->CustomerSupplier->listSupplierByCustomerId($this->Auth->user('customer_id'), array('has_cust_inventory' => true));
        $this->set('suppliers', $suppliers);
        $this->set('supplierBrands', $this->Brand->find('list', array('conditions' => array('supplier_id' => array_keys($suppliers)), 'order' => 'name')));

        $itsBrands = $this->CustProductSite->listItsBrandByCustomerId($this->Auth->user('customer_id'));
        $this->set('itsBrands', $this->Brand->find('list', array('conditions' => array('id' => $itsBrands), 'order' => 'name')));
        $this->set('allBrands', $this->Brand->find('list', array(
                    'conditions' => array(
                        'OR' => array(
                            array('id' => $itsBrands),
                            array('supplier_id' => array_keys($suppliers))
                        )
                    ),
                    'order' => 'name')));

        // ลบ session ที่เก็บค่าตอน search ไว้ print ออก
        $this->Session->delete('Criteria');
        $this->Session->delete('Operand');

        if ($this->viewSiteInventoryId == 'All') {
            $this->render('popup_search_all');
        } else {
            $this->render('popup_search');
        }
    }

    /**
     * ถูกเรียกมาจากหน้า home ของ Supplier หรือ customer
     * ใช้เพื่อให้ Supplier กำหนดหรือลบวันที่คาดว่าจะเติมของให้ลูกค้าได้
     *
     */
    function set_replenish_date($id, $date = null, $month = null, $year = null) {
        $this->CustProductSite->id = $id;
        if ($date != null) {
            $this->CustProductSite->saveField('replenish_date', $date . '/' . $month . '/' . $year);
        } else {    // clear วันที่
            $this->CustProductSite->saveField('replenish_date', null);
        }

        $this->layout = 'ajax';
        $this->set('value', $this->CustProductSite->field('replenish_date'));
        $this->viewPath = 'elements';
        $this->render('ajax/inplace_editor');
    }

    /**
     * ใช้กับ max_stock_note
     * @param string $field
     * @param int $id
     */
    function inplace_editor($field, $id) {
        parent::inplace_editor($this->CustProductSite, $field, $id);

        // ถ้าใส่เป็นค่าว่างเข้ามา ตอบกลับแบบนี้
        $value = trim($this->params['form']['value']);
        if (empty($value)) {
            echo '...';
        }
    }

    /**
     * รายการ brand ทั้งหมด ที่ลูกค้านี้สามารถดูเห็นได้ ที่ถูกส่งมาจาก ITS
     */
    function option_its_brand_list() {
        $suppliers = $this->CustProductSite->listSupplierByCustomerId($this->Auth->user('customer_id'));
        $brands = $this->CustProductSite->Product->Brand->find('list', array('conditions' => array('supplier_id' => $suppliers), 'order' => 'name'));
        parent::option_list($brands);
    }

    /**
     * รายการ brand ทั้งหมด ที่ลูกค้านี้สามารถดูเห็นได้ ที่ถูกส่งมาจาก Vendor
     */
    function option_vendor_brand_list($supplier_id) {
        $brands = $this->Brand->find('list', array('conditions' => array('supplier_id' => $supplier_id), 'order' => 'name'));
        parent::option_list($brands);
    }

    function print_display($site_id) {
        $this->layout = 'print';
        $this->_setReportNote();
        if ($site_id == 'All') {
            $this->paginate['Product']['limit'] = 9999;
            $this->display_all();

            $this->render('print_display_all');
        } else {
            $this->paginate['CustProductSite']['limit'] = 9999;
            $this->display_site();
            $this->render('print_display_site');
        }
    }

    function excel_display($site_id) {
        parent::excel('VMI CUSTOMER INVENTORY');

        $this->_setReportNote();
        if ($site_id == 'All') {
            $this->paginate['Product']['limit'] = 9999;
            $this->display_all();

            $this->render('excel_display_all');
        } else {
            $this->paginate['CustProductSite']['limit'] = 9999;
            $this->display_site();
            $this->render('excel_display_site');
        }
    }

    function _setReportNote() {
        $this->Customer->id = $this->Auth->user('customer_id');
        $this->set('customer_no', $this->Customer->field('cust_no'));
        $this->set('customer_name', $this->Customer->field('name'));
        $this->Site->id = $this->Auth->user('site_id');
        $this->set('site_no', $this->Site->field('site_no'));
        $this->set('site_name', $this->Site->field('name'));
        $this->set('report_by', $this->Auth->user('name'));
        $this->set('print_orientation', PRINT_LANDSCAPE);
    }

    /**
     * popup นี้จะเหมือนหน้า display เอามาแสดงเป็น popup สามารถเลือก product แล้วส่ง stock code กลับไปหน้าที่เรียกมาได้
     */
    function popup_view() {
        $this->layout = 'popup';
        // clear session การ search จากครั้งก่อน
        $this->Session->delete($this->name);

        $this->set('categories', $this->Category->listCategoryBySiteOrSupplier($this->Auth->user('site_id'), $this->Auth->user('supplier_id')));

        $suppliers = $this->CustomerSupplier->listSupplierByCustomerId($this->Auth->user('customer_id'), array('has_cust_inventory' => true));
        $this->set('suppliers', $suppliers);
        $this->set('supplierBrands', $this->Brand->find('list', array('conditions' => array('supplier_id' => array_keys($suppliers)), 'order' => 'name')));

        $itsBrands = $this->CustProductSite->listItsBrandByCustomerId($this->Auth->user('customer_id'));
        $this->set('itsBrands', $this->Brand->find('list', array('conditions' => array('id' => $itsBrands), 'order' => 'name')));

        $this->set('popupTitle', 'Select a Product');
        $this->set('popupWidth', '$j(document).width() - 100');
    }

    /**
     * ใช้ร่วมกับ popup_view เป็นส่วนตารางแสดงแถว customers
     */
    function popup_paginate() {
        if (!isset($this->data['limit'])) {
            $this->data['limit'] = 10;
        }
        $this->display_site();
    }

}

?>